import 'package:flutter/material.dart';

///  共享状态管理 InheritedWidget的使用
main() => runApp(MyApp());

class HYCounterWidget extends InheritedWidget {
  //1.共享的数据
  final int counter;

  //2.定义构造方法
  HYCounterWidget({this.counter, Widget child}) : super(child: child);

  //3.获取组件最近的当前InheritedWidget
  static HYCounterWidget of(BuildContext context) {
    // 沿着Element树，去找到最近的HYCounterElement，从Element中取出widget对象
    return context.dependOnInheritedWidgetOfExactType();
  }

  //4.决定要不要回调State中的didChangeDependencies
  /// 如果返回为true：执行依赖当期的InheritedWidget的State中的didChangeDependencies
  @override
  bool updateShouldNotify(HYCounterWidget oldWidget) {
    return this.counter != oldWidget.counter;
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(primaryColor: Colors.teal, cardColor: Colors.orange),
      debugShowCheckedModeBanner: false,
      home: HYHomePage(),
    );
  }
}

class HYHomePage extends StatefulWidget {
  @override
  _HYHomePageState createState() => _HYHomePageState();
}

class _HYHomePageState extends State<HYHomePage> {
  int _counter = 100;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('InheritedWidget的使用'),
      ),
      body: HYCounterWidget(
        counter: _counter,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [HYShowData01(), HYShowData02()],
          ),
        ),
      ),
      backgroundColor: Colors.white,
      floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          backgroundColor: Colors.teal,
          onPressed: () {
            setState(() {
              _counter++;
            });
          }),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
    );
  }
}

class HYShowData01 extends StatefulWidget {
  @override
  _HYShowData01State createState() => _HYShowData01State();
}

class _HYShowData01State extends State<HYShowData01> {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('_HYShowData01State didChangeDependencies');
  }

  @override
  Widget build(BuildContext context) {
    int count = HYCounterWidget.of(context).counter;
    return Card(
        color: Colors.teal,
        child: Text('当前计数:$count',
            style: TextStyle(fontSize: 30, color: Colors.white)));
  }
}

class HYShowData02 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    int count = HYCounterWidget.of(context).counter;
    return Container(
        color: Colors.blue,
        child: Text('当前计数:$count',
            style: TextStyle(fontSize: 30, color: Colors.white)));
  }
}
